package com.zhang.apipassenger.constraints;

import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 类功能描述
 *
 * @author Kye
 * @date 2025-09-22
 */
public class DateTimeRangeValidator implements ConstraintValidator<DateTimeRange, Object> {
	private DateTimeRange dateTimeRange;
	private String judge;

	@Override
	public void initialize(DateTimeRange constraintAnnotation) {
		judge = constraintAnnotation.judge();
		ConstraintValidator.super.initialize(constraintAnnotation);
	}

	@Override
	public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
		// 用户传递进来的日期参数
		LocalDateTime dateValue = null;
		if (o == null) {
			return true;
		}
		if (o instanceof LocalDateTime) {
			dateValue = (LocalDateTime) o;
		}

		if (o instanceof String) {
			dateValue = LocalDateTime.parse((String) o, DateTimeFormatter.ofPattern(dateTimeRange.pattern()));
		}

		LocalDateTime now = LocalDateTime.now();
		if (judge.equals(DateTimeRange.IS_AFTER) && dateValue.isAfter(now)) {
			return true;
		}
		if (judge.equals(DateTimeRange.IS_BEFORE) && dateValue.isBefore(now)) {
			return true;
		}
		return false;
	}
}
